//
//  AccountViewController.m
//  Ufan
//
//  Created by lori on 15/12/27.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "AccountViewController.h"
#import "QLCache.h"
#import "UIView+KGViewExtend.h"
#import "LeftOrderVC.h"
#import "LeftAboutVC.h"
#import "AccountCell.h"
#import "SuggestionVC.h"
#import "UDImageLabelButton.h"
#import "SettingViewController.h"

#define DOWN_VIEW_HEIGHT 200.f
#define DOWN_Button_BaseTag 40

@interface AccountViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) NSArray *showArray;
@property (strong, nonatomic) UITableView *showTableView;

@property (strong, nonatomic) UIView *headView;
@property (strong, nonatomic) UILabel *accountLabel;

@property (strong, nonatomic) UIView *downView;
@property (nonatomic, strong) NSArray *downButtonArray;

@property (strong, nonatomic) UIView *alphaView;
@end

@implementation AccountViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.alphaView removeFromSuperview];
    [self.downView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:kHttpStateLoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccess) name:kHttpStateLogoutSuccess object:nil];
    
    [self setupBarButtonItem];
    
    self.alphaView.hidden = YES;
    [self.navigationController.view addSubview:self.alphaView];
    [self.view addSubview:self.showTableView];
    
    [self.navigationController.view addSubview:self.downView];
}

- (void)setupBarButtonItem{
    self.title = @"我的账户";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapHead{
    if ([AppPublic shareInstanceApp].Token) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"确定退出?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else{
        [[AppPublic shareInstanceApp] presentLoginVC:self.navigationController];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //退出登录
        [AppPublic doLogout];
    }
    
}

- (void)loginSuccess{
    self.accountLabel.text = [AppPublic shareInstanceApp].Token ? [AppPublic shareInstanceApp].username_password.username : @"登录/注册";
}

- (void)logoutSuccess{
    self.accountLabel.text = [AppPublic shareInstanceApp].Token ? [AppPublic shareInstanceApp].username_password.username : @"登录/注册";
}

- (void)dismissDownView{
    [self showDownView:NO];
}
- (void)showDownView:(BOOL)isShow{
    CGPoint centerPoint = self.downView.center;
    if (isShow) {
        centerPoint.y = self.downView.superview.height - 0.5 * self.downView.height;
    }
    else{
        centerPoint.y = self.downView.superview.height + 0.5 * self.downView.height;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2f];
    self.downView.center = centerPoint;
    self.alphaView.hidden = !isShow;
    [UIView commitAnimations];
}

- (void)buttonClick:(UIButton *)sender {
    
    switch (sender.tag) {
            
        case 11:{
            //取消
            [self showDownView:NO];
        }
            break;
            
        case 40:{
            //电话客服
            [self showDownView:NO];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:028-61075748"]];
        }
            break;
            
        default:
            break;
    }
}

#pragma getter
- (UITableView *)showTableView{
    if (!_showTableView) {
        _showTableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
        _showTableView.multipleTouchEnabled = YES;
        _showTableView.dataSource = self;
        _showTableView.delegate = self;
        _showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_showTableView setBackgroundColor:[UIColor whiteColor]];
        _showTableView.tableHeaderView = self.headView;
    }
    
    return _showTableView;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width * 9.0 / 16.0)];
        [_headView setBackgroundColor:[UIColor blackColor]];
        
        double height = 10000;
        UIView *blackView = [[UIView alloc]initWithFrame:CGRectMake(0, -height, _headView.width, height + _headView.height)];
        blackView.backgroundColor = [UIColor blackColor];
        [_headView addSubview:blackView];
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
        imageView.image = [UIImage imageNamed:@"app_icon"];
        imageView.center = CGPointMake(0.5 * _headView.width, 0.5 * _headView.height - 0.8 * imageView.height);
        [_headView addSubview:imageView];
        imageView.layer.cornerRadius = 0.5 * imageView.width;
        imageView.layer.masksToBounds = YES;
        
        
        self.accountLabel.center = CGPointMake(0.5 * _headView.width, 0.5 * _headView.height);
        [_headView addSubview:self.accountLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHead)];
        [_headView addGestureRecognizer:tap];
        
        
        
    }
    
    return _headView;
}

- (UILabel *)accountLabel{
    if (!_accountLabel) {
        _accountLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.width - 40, 20)];
        _accountLabel.textColor = [UIColor whiteColor];
        _accountLabel.font = [UIFont systemFontOfSize:16.0];
        _accountLabel.textAlignment = NSTextAlignmentCenter;
        _accountLabel.text = [AppPublic shareInstanceApp].Token ? [AppPublic shareInstanceApp].username_password.username : @"登录/注册";
    }
    
    return _accountLabel;
}

- (NSArray *)showArray{
    if (!_showArray) {
        _showArray = @[@{@"title":@"订单",@"subTitle":@"",@"headImage":@"account_00"},
                       @{@"title":@"设置",@"subTitle":@"",@"headImage":@"account_01"},
                       @{@"title":@"关于",@"subTitle":@"",@"headImage":@"account_02"},
                       @{@"title":@"反馈",@"subTitle":@"",@"headImage":@"account_03"},
                       @{@"title":@"联系客服",@"subTitle":@"",@"headImage":@"account_04"}];
    }
    
    return _showArray;
}

- (NSArray *)downButtonArray{
    if (!_downButtonArray) {
        _downButtonArray = @[@{@"title":@"电话客服",@"image":@"account_04"}];
    }
    
    return _downButtonArray;
}

- (UIView *)downView{
    if (!_downView) {
        _downView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, DOWN_VIEW_HEIGHT)];
        _downView.backgroundColor = [UIColor whiteColor];
        
        
        double cellWidth = _downView.width / (2.0 * self.downButtonArray.count);
        
        for (int i = 0; i < self.downButtonArray.count; i++) {
            UDImageLabelButton *button = [[UDImageLabelButton alloc]initWithFrame:CGRectMake(0, 0, 70, 100)];
            button.backgroundColor = [UIColor clearColor];
            
            NSDictionary *dic = self.downButtonArray[i];
            button.upImageView.layer.borderWidth = 1;
            button.upImageView.layer.borderColor = [UIColor blackColor].CGColor;
            button.upImageView.layer.cornerRadius = 0.5 * button.upImageView.width;
            button.centerImageView.image = [UIImage imageNamed:dic[@"image"]];
            button.downLabel.text = dic[@"title"];
            
            button.tag = DOWN_Button_BaseTag + i;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

            
            button.center = CGPointMake(cellWidth * (1 + 2 * i), 20 + 0.5 * button.height);
            [_downView addSubview:button];
        }
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, _downView.height - 61, _downView.width, 1)];
        lineView.backgroundColor = UFCOLOR_GRAYLINE;
        [_downView addSubview:lineView];
        
        UIButton *saveButton = [[UIButton alloc]initWithFrame:CGRectMake(0, _downView.height - 60, _downView.width, 60)];
        [saveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [saveButton setBackgroundColor:[UIColor clearColor]];
        saveButton.titleLabel.font = [UIFont systemFontOfSize:18.0];
        [saveButton setTitle:@"取消" forState:UIControlStateNormal];
        saveButton.tag = 11;
        [saveButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_downView addSubview:saveButton];
    }
    
    return _downView;
}

- (UIView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _alphaView.backgroundColor = RGBA(0, 0, 0, 0.4);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissDownView)];
        [_alphaView addGestureRecognizer:tap];
    }
    
    return _alphaView;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.showArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"accountCell";
    AccountCell *cell = (AccountCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[AccountCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.showTwoLines = (indexPath.row == 2);
    }
    
    
    NSDictionary *dic = self.showArray[indexPath.row];
    cell.textLabel.text = dic[@"title"];
    cell.imageView.image = [UIImage imageNamed:dic[@"headImage"]];
    
    return cell;
}


#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [AccountCell tableView:tableView heightForRowAtIndexPath:indexPath];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
            //订单
        case 0:{
            if ([AppPublic shareInstanceApp].Token) {
                [AppPublic shareInstanceApp].needRefreshOrderList = YES;
                LeftOrderVC *orderVC = [LeftOrderVC new];
                
                [self.navigationController pushViewController:orderVC animated:YES];
            }
            else{
                [[AppPublic shareInstanceApp] presentLoginVC:self.navigationController];
            }
        }
            break;
            
            //设置
        case 1:{
            SettingViewController *vc = [SettingViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
            //关于
        case 2:{
            LeftAboutVC *aboutVC = [LeftAboutVC new];
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
            break;
            
            //反馈
        case 3:{
            SuggestionVC *vc = [SuggestionVC new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
            //联系客服
        case 4:{
            [self showDownView:YES];
        }
            break;
            
        default:
            break;
    }
}


@end
